package top.lunarye.handler.deduplication.service;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import top.lunarye.common.domaim.TaskInfo;
import top.lunarye.handler.deduplication.DeduplicationHolder;
import top.lunarye.handler.deduplication.DeduplicationParam;
import top.lunarye.handler.deduplication.limit.LimitService;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Set;

/**
 * @author lunar
 * @since 2022-07-20
 */
@Slf4j
public abstract class AbstractDeduplicationService implements DeduplicationService {

    protected Integer deduplicationType;

    protected LimitService limitService;

    @Resource
    private DeduplicationHolder deduplicationHolder;

    @PostConstruct
    private void init() {
        deduplicationHolder.putService(deduplicationType, this);
    }

    public void deduplication(DeduplicationParam param) {
        TaskInfo taskInfo = param.getTaskInfo();

        // 得到所有符合去重条件的接收者
        Set<String> filterReceiver = limitService.limitFilter(this, taskInfo, param);

        // 剔除所有符合去重条件的接收者
        if (CollUtil.isNotEmpty(filterReceiver)) {
            taskInfo.getReceiver().removeAll(filterReceiver);
        }
    }

    /**
     * 构建去重的key
     * @param taskInfo
     * @param receiver
     * @return
     */
    public abstract String deduplicationSingleKey(TaskInfo taskInfo, String receiver);

}
